package com.changli02.tcpudp.chat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class chatClientTest {


    public static void main(String[] args)  throws  Exception{
//        InetAddress inet = InetAddress.getByName("10.151.166.121");//10.151.166.121
        int port = 8989;
        //连接服务器
        Socket socket = new  Socket("127.0.0.1",port);

        //开启两个线程
        //一个负责看别人聊天 即接收服务器转发消息
        Receive receive = new Receive(socket);
        receive.start();

        //一个线程负责 自己发送对话
        Send send = new Send(socket);
        send.start();

        send.join();//等发送线程结束。才结束整个线程
        socket.close();



    }
}

class Send extends Thread{
    private Socket socket;

    public Send(Socket  socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            //从键盘获取输入信息
            Scanner input = new Scanner(System.in);
            //Socket的输出流
            OutputStream  os = socket.getOutputStream();

            //将Socket的输出流 放入 打印流
            //按行打印
            PrintStream ps = new PrintStream(os);
            //循环
            while(true){
                System.out.print("自己的话(我):");

                String msg = input.nextLine();
                if("bye".equals(msg)){
                    break;
                }
                ps.println(msg);
            }
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Receive extends Thread{
     private Socket socket;

     public Receive(Socket socket) {
         super();
         this.socket = socket;
     }



     @Override
    public void run (){
         InputStream is = null;

         try {
             is = socket.getInputStream();
             Scanner input = new Scanner(is);
//             int len ;
//             byte [] buffer = new byte[1024];
//             while ((len =is.read(buffer) )!=-1){
//                 System.out.println(new String(buffer,0,len));
//             }
             while (input.hasNextLine()){
                 System.out.println(input.nextLine());
             }


         } catch (IOException e) {
             e.printStackTrace();
         }
         //不用关 ，可能还没有接受完，那边还在发送
//         finally {
//             try {
//                 is.close();
//             } catch (IOException e) {
//                 e.printStackTrace();
//             }
//         }
     }
}
